package com.lsh.netty.echo.mydelimiterbasedframedecoder;

import com.lsh.msgpack.MsgpackDecoder;
import com.lsh.msgpack.MsgpackEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/4/6 12:50 下午
 * @desc ：DelimiterBasedFreamDecoder应用开发 可以自动完成以分隔符作为码流结束标识的消息的解码
 * EchoClient客户端实现
 * EchoServer接收到EchoClient的请求消息后，将其打印出来，然后将原始消息返回给客户端，消息以"$_"作为分隔符
 */
public class EchoClient {
    public void connect(int port,String host) throws Exception{
        //配置Nio线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new EchoClientHandler());
                            ch.pipeline().addLast("msgpack decoder",new MsgpackDecoder());
                            ch.pipeline().addLast("msgpack encoder",new MsgpackEncoder());
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();
            //等待客户端链路关闭
            f.channel().closeFuture().sync();

        }finally {
            //优雅退出，释放线程组资源
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        String host = "127.0.0.1";
        new EchoClient().connect(port,host);
    }
}
